import { useRequest } from 'umi';
import { requestFunComponFiex } from '@/utils';
import { useCallback, useState } from 'react';
import { loadMdicIds } from './DictionaryService';
import { getBaseUrl } from '@/services/urlconst';
import { YSX_STATE } from '../common/Format';

const baseUrl = getBaseUrl();

export const NeedManageService = () => {
  // 管理页列表接口
  const getNeedManageService = () => {
    /***保存当前的搜索参数**/
    const [manageTableParams, setManageTableParams] = useState<Record<string, any>>({});
    const request = useRequest(
      (requestParams?: Record<string, any>) => {
        const reqUrl = `${baseUrl}/purchaseNeedController/dataGrid/${requestParams?.params}`;
        let params: any = {
          current: 1,
          pageSize: 10,
          ...requestParams,
          dicTypeIds: loadMdicIds()?.join(','),
          notShow: YSX_STATE(),
          sort: 'createTime',
          order: 'desc',
        };

        delete params['applyFormNameDept'];
        delete params['applyFormNameUser'];

        if (params['createrID']?.length) {
          params['createrID'] = params['createrID']?.toString();
        } else {
          delete params['createrID'];
        }

        // 处理作废时间
        if (params?.cancelTime) {
          const [cancelTimeStart, cancelTimeEnd] = params.cancelTime;
          params['cancelTimeStart'] = cancelTimeStart.format('YYYY-MM-DD 00:00:00');
          params['cancelTimeEnd'] = cancelTimeEnd.format('YYYY-MM-DD 23:59:59');
          delete params['cancelTime'];
        }

        // 处理创建时间
        if (params?.createTime) {
          const [createTimeStart, createTimeEnd] = params.createTime;
          params['createTimeStart'] = createTimeStart.format('YYYY-MM-DD 00:00:00');
          params['createTimeEnd'] = createTimeEnd.format('YYYY-MM-DD 23:59:59');
          delete params['createTime'];
        }

        /***保存一份参数**/
        setManageTableParams(params);
        return requestFunComponFiex('POST', reqUrl, params);
      },
      {
        manual: false,
        paginated: true,
        defaultPageSize: 10,
      },
    );

    const reloadRequest = useCallback((reqParams: any) => {
      // 创建时间处理
      delete reqParams['createFormNameDept'];
      delete reqParams['createFormNameUser'];
      if (reqParams?.createrID && reqParams?.createrID?.length > 0) {
        reqParams['createrID'] = reqParams?.createrID?.toString();
      } else {
        delete reqParams['createrID'];
      }
      let reqObj = {
        ...reqParams,
      };
      request?.run(reqObj);
    }, []);
    return {
      needManageRun: request.run,
      needManageDataSource: request.data?.rows || [],
      needManageLoading: request.loading,
      needManageTableProps: request.tableProps,
      reloadRequest: reloadRequest,
      reloadRequests: request?.refresh,
      manageTableParams,
    };
  };

  return {
    getNeedManageService,
  };
};
